﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Sitecore.Data.Items;
using System.Data;
using Workflow.Alerts.DAL;
using Workflow.Alerts.Interfaces.ProfileSettings;

namespace Workflow.Alerts
{
    public class MaterialsDtlsPresenter : Presenter
    {
        #region members
        private readonly MaterialsViewDAL model;
        private readonly IMaterialsDtlsView view;
        #endregion

        #region constructor
        public MaterialsDtlsPresenter(IMaterialsDtlsView _view)
            : this(_view, null)
        { }

        public MaterialsDtlsPresenter(IMaterialsDtlsView _view, ISessionProvider session)
            : base(_view, session)
        {
            view = base.GetView<IMaterialsDtlsView>();
            view.OnPageLoad += view_OnLoad;
            view.OnUpdate += view_OnUpdate;
            model = new MaterialsViewDAL();
        }

        #endregion

        #region private methods

        private void view_OnLoad()
        {
            BindUnits();

            if (view.Id.HasValue)
            {
                //retrieve details of existing material                
                var filter = new WorkflowFilter
                {
                    MaterialsId = view.Id
                };

                var filterSql = new WorkflowFilterSql(filter);

                EstateDataSet.MaterialsDataTable materials = model.GetMaterialsDetails(filterSql);

                if (materials.Rows.Count == 1)
                {
                    EstateDataSet.MaterialsRow material = materials[0];
                    view.Name = material.name;
                    view.Disable = material.disabled;
                    view.Price = (float?)material.price;
                    view.Unit = material.unit;
                    view.ConstructorPrice = (float?)material.constructorprice;
                }
            }
        }

        private void BindUnits()
        {
            view.Units = WorkflowEnums.MaterialsUnits;
        }

        private bool view_OnUpdate()
        {
            var filter = new WorkflowFilter
            {
                MaterialsId = view.Id,
                MunicipalityId = CurrentUser.TypeId,
                Name = view.Name,
                Price = view.Price,
                Unit = view.Unit,
                Disabled = view.Disable,
                ConstructorPrice = view.ConstructorPrice
            };

            var filterSql = new WorkflowFilterSql(filter);

            if (view.Id.HasValue)
            {
                return model.UpdateMaterial(filterSql);
            }
            else
            {
                return model.CreateMaterial(filterSql);
            }
        }

        #endregion
    }
}
